#!/usr/bin/python



from google.appengine.ext import webapp
from google.appengine.ext import db

from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app

class Visitor(db.Model):
	
	content = db.StringProperty(multiline=True)
	date = db.DateTimeProperty(auto_now_add=True)
	writer = db.StringProperty()
	avatar = db.BlobProperty()
	

class MainPage(webapp.RequestHandler):
	
	def get(self):
		
		self.response.out.write(template.render('templates/main.mako',{}))
	
class Guestbook(webapp.RequestHandler):
	
    	error_writer_too_long = False
	error_content_too_long = False
        def get(self):
                visitors = db.GqlQuery("SELECT * FROM Visitor ORDER BY date DESC")
	
		counter=visitors.count()
		if(not (counter % 5)):
			pages = range(counter/5)
		else:
			pages = range(counter/5+1)

		page = self.request.get('page')
		try:
			page = int(page)
		except ValueError:
			page = 0
		offset = (page) * 5
		if offset < 0: offset = 0

		if (cookie_exists(self,'username')):
			nombre = get_cookie(self,'username')
		else:
			nombre = ''
			
		visitors = visitors.fetch(5, offset)

		guestbook_values = {
			'nombre' : nombre,
			'visitors': visitors,
			'counter': counter,
			'pages': pages,
			}

        	self.response.out.write(template.render('templates/guestbook.mako', guestbook_values))


  
class Messaging(webapp.RequestHandler):
        
	
	def post(self):
                visitor = Visitor()
		
                if self.request.get('writer'):
                        writer = cgi.escape(self.request.get('writer'))
			if (len(writer)>15):
				error_writer_too_long = True
			else:
				error_writer_too_long = False
				visitor.writer = writer
     
                content = cgi.escape(self.request.get('content'))
		if (len(content)>450):
			error_content_too_long = True
		else:
			error_content_too_long = False
			visitor.content = content
		
		
		try:
			avatar = images.resize(self.request.get("img"), 48, 48)
			visitor.avatar = db.Blob(avatar)
		except:
			visitor.avatar = None
		
		if (not (error_writer_too_long or error_content_too_long )):
               		visitor.put()
                self.redirect('/guestbook')

class Error(webapp.RequestHandler):
			
	def get(self):
		self.response.out.write(template.render('templates/error.mako',{}))

		
def main():
	
	app = webapp.WSGIApplication(
				[
				('/' , MainPage),
				('/guestbook' , Guestbook),
				('/sign' , Messaging),
				('/.*' , Error),
				
				],
				debug = True)
					
	run_wsgi_app(app)
					
if __name__ == "__main__":
	main()

